<!--
 * @Description: 角色管理页面
-->
<template>
  <MainSlot class="patrol-point-manage">
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" @search="(e) => {
        (searchlist = { ...e }), (currentPage = 1), getTableDataList();
      }">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <TableData @selection-change="selectionChange" :config="table_config" :tableThead="tableThead"
        :dataList="dataList">
        <template v-slot:userNames="{ row }">
          <span>{{ row.userNames && row.userNames.length ? row.userNames.join(",") : "--" }}</span>
        </template>
        <template v-slot:description="{ row }">
          <span>{{ row.description || '--' }}</span>
        </template>

        <template v-slot:roleNo="{ row }">
          <el-button class="text-btn-cursor" type="text" size="small" @click="funcAuthShow(row, true)">查看权限</el-button>
        </template>
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination  @size-Change="handleSizeChange" :size="pageSize"  @current-change="handleCurrentChange" :page="currentPage" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal="false" :title="titleText + '角色'" :visible.sync="dialogFormVisible" width="40%"
        :before-close="cancel">
        <el-form ref="formData" :model="formData" :rules="rules" label-width="100px" class="demo-ruleForm">
          <el-form-item label="角色名称" prop="roleName" class="w100p">
            <el-input v-model="formData.roleName" clearable />
          </el-form-item>
          <el-form-item label="描述" prop="description" class="w100p">
            <el-input v-model="formData.description" clearable />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">
            保 存
          </el-button>
        </div>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" title="分配功能权限" :visible.sync="dialogDataAuthFormVisible" width="60%"
        :before-close="cancel">
        <DataAuthComponent v-if="dialogDataAuthFormVisible" ref="funcAppAuth" :role-no="formData.roleNo"
          :rolestu="rolestu" :auth-disabled="authDisabled" @roles="roles" />
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-two" type="primary" @click="saveRole('formData')">
            关 闭
          </el-button>
        </div>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" title="分配App功能权限" :visible.sync="dialogDataAppAuthFormVisible"
        width="40%">
        <DataAppAuthComponent v-if="dialogDataAppAuthFormVisible" ref="funcAuth" :role-no="formData.roleNo"
          :rolestu="rolestu" @roles="roles" />
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel"> 取 消 </el-button>
          <el-button class="zh-button-two" type="primary" @click="saveRole('formData')">
            保 存
          </el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import Pagination from "@/components/Pagination";
import SearchForm from "@/components/SearchForm";
import TableData from "@/components/TableData";
import BtnSlot from "@/components/BtnSlot";

import DataAuthComponent from "../components/func-auth-component.vue";
import DataAppAuthComponent from "../components/App-auth-component.vue";
import roleManage from "@/api/system-settings/role-manage";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";

export default {
  name: "RoleManage",
  components: {
    SearchForm,
    BtnSlot,
    Pagination,
    DataAuthComponent,
    DataAppAuthComponent,
    MainSlot,
    TableData,
  },
  mixins: [mymixin],
  data() {
    return {
      formItemList: [
        {
          label: "角色名称",
          type: "input",
          param: "roleName",
          isShow: true,
        },
      ], //搜索
      searchlist: [],
      selectionList: [],
      tableThead: [
        { isShow: true, label: "角色名称", prop: "roleName" },
        { isShow: true, label: "描述", slotName: "description" },
        { isShow: true, label: "用户列表", slotName: "userNames" },
        { isShow: true, label: "权限列表", slotName: "roleNo" },
      ],
      btnList: ["add"],
      selectIndex: 0,
      total: 100,
      currentPage: 1,
      dataList: [],
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: "操作",
          width: "200",
          cols: [
            {
              label: "功能权限",
              type: "primary",
              flag: "permission",
              handleRow: this.handleRow,
            },
            {
              label: "修改",
              type: "default",
              flag: "edit",
              handleRow: this.handleRow,
            },
          ],
        },
      },
      //   ===========================cv
      // 操作按钮的逻辑及展示数据
      addActive: true,
      editActive: false,
      delActive: false,
      saveActive: false,
      cancelActive: false,
      dataAuthActive: false,
      funcAuthActive: false,
      funcAppAuthActive: false,
      dialogDataAppAuthFormVisible: false,
      authDisabled: false,
      // table
      loading: true,
      // 当前页
      currentPage: 1,
      // 每页的数据条数
      pageSize: 10,
      // 总条数
      totalSize: 0,
      // 角色名称
      roleName: "",
      nowpage: 1,
      // 是否能输入
      canInput: false,
      tableData: [],
      rolestu: "",
      formData: {},
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      // 选中的数据项数组 ID组成
      roleIdList: [],
      dialogTitle: "",
      dialogFormVisible: false,
      dialogDataAuthFormVisible: false,
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {},
  async created() {
    // 获取表格数据
    await this.getTableDataList();
  },
  mounted() { },
  methods: {
    // 多选方法
    selectionChange(val) {
      this.selectionList = val || [];
    },
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "add") {
        this.add();
      } else if (flag == "permission") {
        if (this.selectionList.length == 1) {
          this.funcAppAuthShow();
        } else {
          this.$message.warning("请选择单个数据项");
        }
      }
    },
    handleCurrentChange(val) {
      console.log(val);
      this.currentPage = val;
      this.getTableDataList();
    },
    handleSizeChange(size){
      this.pageSize = size;
      this.getTableDataList();
    },
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == "edit") {
        this.edit(rowData);
      } else if (item.flag == "permission") {
        this.formData = rowData;
        this.funcAuthShow(rowData, false);
      }
    },
    async getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          roleName: this.roleName,
        },
      };
      const { data: res } = await roleManage.getPageList(params);
      this.loading = false;
      let data = res;
      // 赋值总条数
      this.total = data.totalElements;
      // 赋值数组
      this.dataList = data.content || [];
      this.addblankmet();
      this.dialogFormVisible = false;
    },
    saveRole() {
      this.dialogDataAuthFormVisible = false;

      this.funcAuthActive = false;
      // this.rolestu = 'add'
    },
    roles() {
      this.rolestu = "";
      this.dialogDataAuthFormVisible = false;
      this.dialogDataAppAuthFormVisible = false;
    },
    // 填充表格空白行
    addblankmet() {
      let havline = this.tableData.length % this.pageSize;
      if (this.tableData.length < this.pageSize) {
        if (havline < this.pageSize) {
          const remain = this.pageSize - havline;
          for (var i = 0; i < remain; i++) {
            this.tableData.push({ indflag: i + this.tableData.length - 1 });
          }
        }
      }
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    handleEdit(row) {
      this.formData = JSON.parse(JSON.stringify(row));
      if (row.roleNo) {
        this.funcAuthActive = true;
        this.cancelActive = true;
        this.funcAppAuthActive = true;
      } else {
        this.resetActionBar();
      }
      // this.openDialog('add');
    },
    handleSelectionChange(list) {
      this.roleIdList = [];
      this.roleIdList = list.map((item) => item.roleNo);
      if (this.roleIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    // add() {
    //   // TODO 添加后 input可输入 add及cancel 1 其余 0
    //   this.canInput = true;
    //   this.addActive = false;
    //   this.editActive = false;
    //   this.delActive = false;
    //   this.saveActive = true;
    //   this.cancelActive = true;
    //   // this.nowpage = 1;
    //   this.dialogFormVisible = true
    //   // roleId置空
    //   // this.formData.roleNo = "";
    // },
    // 初始化操作栏状态
    resetActionBar() {
      this.funcAuthActive = false;
      this.dataAuthActive = false;
      this.assignUserActive = false;
      this.funcAuthActive = false;
      this.funcAppAuthActive = false;
      this.nowpage = 1;
      this.canInput = false;
      this.addActive = true;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false;
    },
    // 点击功能权限触发的方法
    funcAuthShow(data, disabled) {
      this.formData = data;
      this.authDisabled = disabled;
      this.dialogDataAuthFormVisible = true;
      console.log(data, disabled, this.authDisabled);

    },
    funcAppAuthShow() {
      this.dialogDataAppAuthFormVisible = true;
    },
    del(e) {
      this.$message.warning("角色不允许删除");
      // roleManage.allmetInfo({roleNoList: [e]}, "delList").then(res => {
      //   if (res.code === 1) {
      //     this.$message.success(res.msg);
      //     this.getTableDataList();
      //   }
      // });
    },
    cancel() {
      // this.closeDialog();
      this.formData = {};
      this.$nextTick(() => {
        this.$refs["formData"] && this.$refs["formData"].resetFields();
      });
      this.funcAuthActive = false;
      this.dataAuthActive = false;
      this.dialogFormVisible = false;
      this.cancelActive = false;
      this.assignUserActive = false;
      this.funcAuthActive = false;
      this.funcAppAuthActive = false;
      this.addActive = true;
      this.dialogDataAuthFormVisible = false;
      this.dialogDataAppAuthFormVisible = false;
    },
    save(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          if (this.formData.roleNo) {
            // 编辑接口
            roleManage.allmetInfo(this.formData, "edit").then((res) => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                this.formData = {};
                this.getTableDataList();
              }
            });
          } else {
            // 新增接口
            roleManage.allmetInfo(this.formData, "add").then((res) => {
              if (res.code === 1) {
                this.$message.success("新增成功！");
                this.formData = {};
                this.getTableDataList();
              } else {
                this.$message.warning(res.msg);
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
        if (this.formData.id && this.nowpage === 2) {
          this.$refs.funcAuth.setpermission();
          this.resetActionBar();
        } else if (this.nowpage === 3) {
          this.$refs.assignrole.checkchange();
        }
        this.resetActionBar();
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    },
  },
};
</script>

<style scoped lang="scss"></style>
